<script lang="ts" setup>
import type { FormInstance, TreeNodeData } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { EmployeeApi } from '@/apis'
import { useForm, useOrg, useRole } from '@/hooks'
import * as Regexp from '@/utils/regexp'
import CellStatus from '@/components/ProCell/CellStatus.vue'

// 保存
const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<EmployeeApi.EmployeeDetailResp>()
const formRef = ref<FormInstance>()

const { form, resetForm } = useForm({
  name: null,
  nikename: null,
  code: null,
  mobilePhone: null,
  gender: 0,
  status: 1,
  orgId: null,
  type: null,
  roleIdList: [],
})

const rules: FormInstance['rules'] = {
  name: [{ required: true, match: Regexp.Name, message: '姓名只能含有中文、数字、英文、·、空格字符和部分特殊字符，且长度不能超过24位' }],
  code: [{ required: false, match: Regexp.Code, message: '编码只能含有英文、数字、下划线、短横线，以字母开头，长度为2-32位' }],
  mobilePhone: [{ required: true, match: Regexp.Phone, message: '手机号不符合规则' }],
  // password: [{ required: true, message: '请输入密码' }],
  // orgId: [{ required: true, message: '请选择所属部门' }],
  // roleIds: [{ required: true, message: '请选择角色' }]
}

// 角色数据
const { roleList, getRoleList } = useRole()

// 组织数据
const { orgTree, getOrgTree } = useOrg()
const filterOrgOptions = (searchKey: string, nodeData: TreeNodeData) => {
  if (nodeData.title) {
    return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
  }
  return false
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 取消
const onCancel = () => {
  readonly.value = true
  // Object.assign(form, dataDetail.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  await EmployeeApi.update(form, dataId.value)
  Message.success('修改成功')
  emit('change')
  visible.value = false
}

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await EmployeeApi.getDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开面板
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
  if (!orgTree.value.length) {
    getOrgTree()
  }
  if (!roleList.value.length) {
    getRoleList()
  }
}

defineExpose({ open })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="drawer"
    :loading="loading"
    :title="dataDetail?.name || '员工详情'"
    :footer="false"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly size="medium">
      <a-card title="基础信息" class="section">
        <template #extra>
          <ReadonlyEditButton
            :readonly="readonly"
            :deleteable="false"
            @edit="onEdit"
            @cancel="onCancel"
            @save="onSave"
          />
        </template>
        <a-row :gutter="28">
          <readonly-form-item label="员工姓名" field="name">
            <a-input v-model.trim="form.name" placeholder="请输入员工姓名" :max-length="32" />
          </readonly-form-item>
          <readonly-form-item label="员工编码" field="code" tooltip="员工编号指员工唯一标识，一般为工号等。">
            <a-input v-model.trim="form.code" placeholder="请输入员工编码" :max-length="32" />
          </readonly-form-item>
          <readonly-form-item label="手机号码" field="mobilePhone" :copyable="true">
            <a-input v-model.trim="form.mobilePhone" placeholder="请输入手机号码" :max-length="11" />
          </readonly-form-item>
          <readonly-form-item label="性别" field="gender">
            <DictSelect v-model="form.gender" type="radio" code="GenderEnum" />
            <template #readonly>
              <CellGender :gender="dataDetail?.gender" />
            </template>
          </readonly-form-item>
          <readonly-form-item label="类型" field="type">
            <DictSelect
              v-model="form.type"
              placeholder="请选择类型"
              allow-clear
              allow-search
              type="select"
              code="EmployeeTypeEnum"
            />
            <template #readonly>
              <CellDict :value="form.type" code="EmployeeTypeEnum" />
            </template>
          </readonly-form-item>
          <readonly-form-item label="状态" field="status">
            <DictSelect v-model="form.status" code="CommonStatusEnum" type="switch" />
            <template #readonly>
              <CellStatus :status="dataDetail?.status" />
            </template>
          </readonly-form-item>
        </a-row>
      </a-card>
      <a-card title="组织角色" class="section">
        <readonly-form-item label="所属组织" field="orgId">
          <a-tree-select
            v-model="form.orgId"
            :data="orgTree"
            placeholder="请选择组织"
            allow-clear
            allow-search
            :filter-tree-node="filterOrgOptions"
          />
          <template #readonly>
            <a-tag>{{ dataDetail?.orgName }}</a-tag>
          </template>
        </readonly-form-item>
        <readonly-form-item label="所属角色" field="roleIdList" :span="12">
          <a-select
            v-model="form.roleIdList"
            placeholder="请选择角色"
            allow-clear
            multiple
            :scrollbar="true"
          >
            <a-option v-for="role in roleList" :key="role.id" :value="role.id">
              {{ role.name }}
            </a-option>
          </a-select>
          <template #readonly>
            <a-space>
              <a-tag v-for="role in dataDetail?.roleList" :key="role.id">
                {{ role.name }}
              </a-tag>
            </a-space>
          </template>
        </readonly-form-item>
      </a-card>
      <a-card title="安全信息" class="section">
        <a-row :gutter="28">
          <a-col :span="12">
            <a-form-item label="用户名" field="username">
              <span>{{ dataDetail?.username }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最后一次登录时间" field="lastLoginTime">
              <span>{{ dataDetail?.lastLoginTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最后一次登录ip" field="lastLoginIp">
              <span>{{ dataDetail?.lastLoginIp }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最后一次修改密码时间" field="lastPwdModifiedTime">
              <span>{{ dataDetail?.lastPwdModifiedTime || '--' }}</span>
            </a-form-item>
          </a-col>
          <!-- <readonly-form-item label="初始密码" field="password">
            <span>账号正常运行，如遇登录问题请点击 重置密码</span>
          </readonly-form-item> -->
        </a-row>
      </a-card>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped></style>
